'use client';

import type { IPostEditInfo, IPostNewInfo } from '@/interfaces';
import { type ChangeEvent, useContext } from 'react';
import { PostEditContext } from '@/contexts/post-edit';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { updatePostEditInfo } from '@/services/api';

export type TSelectContentTranslatedField =
  | 'sectionIdPlaceholder'
  | 'update'
  | 'updateCompleted';

export default function SelectContent({
  source,
  translatedFields = {
    sectionIdPlaceholder: '请选择内容',
    update: '更新',
    updateCompleted: '更新完成',
  },
}: {
  source: IPostEditInfo | IPostNewInfo;
  translatedFields?: Record<TSelectContentTranslatedField, any>;
}) {
  const context = useContext(PostEditContext);
  const { form, setForm } = context;
  const isEdit = 'basic' in source;
  const sections = source.sections;
  const { show } = useToast();

  const updatePostEditInfoMutation = useMutation(updatePostEditInfo);

  async function onClickUpdate() {
    if (!isEdit) {
      show({
        type: 'SUCCESS',
        message: translatedFields.updateCompleted,
      });
      return;
    }

    try {
      const _form: any = {
        ...form,
      };

      if (!_form.sectionId) {
        show({
          type: 'SUCCESS',
          message: translatedFields.updateCompleted,
        });
        return;
      }

      await updatePostEditInfoMutation.mutateAsync({
        id: source.basic.id,
        data: _form,
      });
    } catch (e) {
      updatePostEditInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChange(e: ChangeEvent<HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <div className="card border-0">
      <div className="card-body d-flex flex-column gap-4 my-4">
        <select
          name="sectionId"
          className="form-select"
          value={form.sectionId}
          onChange={onChange}
          placeholder={translatedFields.sectionIdPlaceholder}
        >
          {sections.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>

        <div className="d-grid col-2">
          <button
            onClick={onClickUpdate}
            type="button"
            className="btn btn-success"
          >
            {translatedFields.update}
          </button>
        </div>
      </div>
    </div>
  );
}
